<?php
/*
This is the only file you need to modify to get your XML-RPC server running.
You need to define constants and build functions according to the comments in this script.
*/

/****************************************
*
*   Global Setup - Used for all methods
*
****************************************/
/*
DEFINE CONSTANT: INTEGRATION_KEY
The following constant must hold the integration key you entered at PBBG Warp.
*/

define('INTEGRATION_KEY', 'teh-key-4-integration');

/*
BUILD FUNCTION: config_dbconnect
The following function must create a connection to your game's database.
The sample code throughout this script assumes a MySQL database, which
you can change if necessary.
*/

function config_dbconnect() {
	global $dal;
	include( '../global/dlog.php' );
	include( '../configuration/config.php' );
	include( '../global/DatabaseAbstractionLayer.php' );
	include( '../global/old_database_connection.php' );
	include( '../global/utils.php' );
	$dal = new DatabaseAbstractionLayer();
	// Set the database abstraction layer to use the same debug setting as used in the config
	$dal->setDebug( DEBUG );
}

/****************************************
*
*   Your XML-RPC Server Method:
*   pbbgwarp.doFanReward_v1
*
****************************************/
/*
DEFINE CONSTANT: IMPLEMENTED_DOFANREWARD_V1
The following constant allows you to enable and disable the pbbgwarp.doFanReward_v1 method on
your server. If you disable the method then you do not need to do any further configuration in
this section.
*** THE METHOD IS DISABLED BY DEFAULT ***
*/

define('IMPLEMENTED_DOFANREWARD_V1', true);

/*
BUILD FUNCTION: config_doFanReward_v1
If you are implementing this method remember to set constant IMPLEMENTED_DOFANREWARD_V1 to true.
This function receives information about a new fan of your game on PBBG Warp issues a reward if
appropriate.
The function receives the screen name on your game of the new fan (only fans who enter a screen
name when becoming a fan will trigger calls to pbbgwarp.doFanReward_v1), and a variable
indicating whether the fan verified their screen name. The function must return a variable
indicating if a reward was given, and a message for the fan.

It is strongly recommended that you check whether the screen name has already claimed a fan
reward to prevent abuse of this system (this requires that you record the rewards that you
issue).

The sample code below assumes you have an Accounts table with a Money column. If the newfan
verified
their screen name then a reward of 50 money is issued.

INPUT:
$inScreenName	String. The screen name (on your game) that your new fan entered on PBBG Warp.
$inVerified		Boolean. Equal to true if the new fan verified their screen name.

OUTPUT:
The function must return an array with two elements:
	rewarded	Boolean. Equal to true only if a reward was issued.
	message		String. A message for the user describing the reward, or explaining why they
	didn't receive one.

*/

function config_doFanReward_v1($inScreenName, $inVerified) {
	global $dal;
	// Issue a reward if the fan verified their screen name
	if ($inVerified) {
		$statement = $dal->prepare( 'SELECT user_id, became_fan ' .
				'FROM users ' .
				'WHERE username = :username' );
		$statement->bindParam( ':username', $inScreenName );
		$user = $dal->getObject( $statement );
		if( $user->became_fan == -1 ) {
			$statement = $dal->prepare( 'UPDATE users ' .
					'SET promotion_points = promotion_points + 100, became_fan = :became_fan ' .
					'WHERE user_id = :user_id' );
			$time = time();
			$statement->bindParam( ':became_fan', $time, PDO::PARAM_INT );
			$statement->bindParam( ':user_id', $user->user_id, PDO::PARAM_INT );
			$dal->execute( $statement );
			$statement = $dal->prepare( 'INSERT INTO vote_reward ' .
					'( `user_id`, `timestamp`, `turn`, `site`, `reward` ) ' .
					'VALUES( :user_id, :timestamp, :turn, :site, :reward )' );
			$statement->bindParam( ':user_id', $user->user_id, PDO::PARAM_INT );
			$timestamp = time();
			$turn = getCurrentTurn();
			$site = 'PBBG Warp user became fan';
			$reward = 100;
			$statement->bindParam( ':timestamp', $timestamp, PDO::PARAM_INT );
			$statement->bindParam( ':turn', $turn, PDO::PARAM_INT );
			$statement->bindParam( ':site', $site, PDO::PARAM_STR );
			$statement->bindParam( ':reward', $reward, PDO::PARAM_INT );
			$dal->execute( $statement );
			return array (
				'rewarded' => true,
				'message' => 'You have been rewarded 100 promotion points for becoming a fan of Ages of Strife.'
			);
		}
		else {
			return array (
				'rewarded' => false,
				'message' => 'Rewards are only issued the first time you become a fan.'
			);
		}
	} else {
		return array (
			'rewarded' => false,
			'message' => 'Rewards are only issued if you verify your screen name.'
		);
	}

} // config_doFanReward_v1

/****************************************
*
*   Your XML-RPC Server Method:
*   pbbgwarp.doVoteReward_v1
*
****************************************/

/*
DEFINE CONSTANT: IMPLEMENTED_DOVOTEREWARD_V1
The following constant allows you to enable and disable the pbbgwarp.doVoteReward_v1 method on
your server. If you disable the method then you do not need to do any further configuration in
this section.
*** THE METHOD IS DISABLED BY DEFAULT ***
*/

define('IMPLEMENTED_DOVOTEREWARD_V1', true);

/*
BUILD FUNCTION: config_doVoteReward_v1
If you are implementing this method remember to set constant IMPLEMENTED_DOVOTEREWARD_V1 to true.
This function receives information about a vote on a satellite ranking and issues a reward if
appropriate.

The function receives the domain name of the satellite ranking on which the vote took place
(in the form "toppbbgs.com" for example), the userid that your web site passed to the satellite
ranking vote script, and a variable indicating whether the vote was successful. The function must
return a variable indicating whether a reward was given, and a message for the voter.

The sample code below assumes you have an Accounts table with a Money column. If a vote is
successful then a reward of 50 money is issued. This sample issues a reward for voting on any
satellite ranking.

INPUT:
$inSatDomain	String. The domain name of the satellite ranking that registered the vote attempt
				(for example "toppbbgs.com").
$inUserID		String. The userid passed to the satellite ranking vote script by your website.
$inVoteCounted	Boolean. Equal to true only if the vote was successfully
				registered (only one vote per player per game per hour is allowed).

OUTPUT:
The function must return an array with two elements:
	rewarded	Boolean. Equal to true only if a reward was issued.
	message		String. A message for the user describing the reward, or explaining why they
				didn't receive one.

*/

function config_doVoteReward_v1($inSatDomain, $inUserID, $inVoteCounted) {
	global $dal;
	// Issue a reward if the fan verified their screen name
	if ($inVoteCounted) {
		$statement = $dal->prepare( 'UPDATE users ' .
				'SET promotion_points = promotion_points + 5 ' .
				'WHERE user_id = :user_id' );
		$time = time();
		$statement->bindParam( ':user_id', $inUserID, PDO::PARAM_INT );
		$dal->execute( $statement );
		$statement = $dal->prepare( 'INSERT INTO vote_reward ' .
				'( `user_id`, `timestamp`, `turn`, `site`, `reward` ) ' .
				'VALUES( :user_id, :timestamp, :turn, :site, :reward )' );
		$statement->bindParam( ':user_id', $inUserID, PDO::PARAM_INT );
		$timestamp = time();
		$turn = getCurrentTurn();
		$site = 'Voted on ' . $inSatDomain;
		$reward = 5;
		$statement->bindParam( ':timestamp', $timestamp, PDO::PARAM_INT );
		$statement->bindParam( ':turn', $turn, PDO::PARAM_INT );
		$statement->bindParam( ':site', $site, PDO::PARAM_STR );
		$statement->bindParam( ':reward', $reward, PDO::PARAM_INT );
		$dal->execute( $statement );
		return array (
			'rewarded' => true,
			'message' => 'You have been rewarded 5 promotion points for voting for Ages of Strife.'
		);
	} else {
		return array (
			'rewarded' => false,
			'message' => 'Only successful votes are rewarded.'
		);
	}
} // config_doVoteReward_v1

/****************************************
*
*   Your XML-RPC Server Method:
*   pbbgwarp.getGameStats_v1
*
****************************************/

/*
DEFINE CONSTANT: IMPLEMENTED_GETGAMESTATS_V1
The following constant allows you to enable and disable the pbbgwarp.getGameStats_v1 method on
your server. If you disable the method then you do not need to do any further configuration in
this section.

*** THE METHOD IS DISABLED BY DEFAULT ***

*/

define('IMPLEMENTED_GETGAMESTATS_V1', false);

/*

BUILD FUNCTION: config_getGameStats_v1_totalPlayers

If you are implementing this method remember to set constant IMPLEMENTED_GETGAMESTATS_V1 to true.

This function retrieves the total number of players on your game.
This function should return false if you do not wish to display this statistic.

The sample code assumes that you have a table called Accounts, and returns a count of
the number of rows in this table. You should modify it to work for your game.

INPUT:
None.

OUTPUT:
Integer. The total number of players on your game.

*/

function config_getGameStats_v1_totalPlayers() {

	// Retrieve the total number of players
	$sql = "SELECT COUNT(*) AS TotalPlayers FROM Accounts";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	return $row['TotalPlayers'];

} // config_getGameStats_v1_totalPlayers

/*
BUILD FUNCTION: config_getGameStats_v1_effectivePlayers
If you are implementing this method remember to set constant IMPLEMENTED_GETGAMESTATS_V1 to true.
This function retrieves the number of effective players on your game. An effective
player is one who signed up more than three days ago, and who has played within the past
two days. This function should return false if you do not wish to display this statistic.
The sample code assumes that you have a table called Accounts with columns called
DateSignup and DateLastLogin.
INPUT:
None.
OUTPUT:
Integer. The number of effective players on your game.
*/

function config_getGameStats_v1_effectivePlayers() {

	// Retrieve the number of effective players
	$sql = "SELECT COUNT(*) AS EffectivePlayers FROM Accounts
			WHERE DateSignup < DATE_ADD(CurDate(), INTERVAL -3 day)
			AND DateLastLogin >= DATE_ADD(CurDate(), INTERVAL -2 day)";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	return $row['EffectivePlayers'];

} // config_getGameStats_v1_effectivePlayers

/*

BUILD FUNCTION: config_getGameStats_v1_onlinePlayers

If you are implementing this method remember to set constant IMPLEMENTED_GETGAMESTATS_V1 to true.

This function retrieves the number of players currently online in your game.
This function should return false if you do not wish to display this statistic.

The sample code assumes that you have a table called Accounts with a column called Online.

INPUT:
None.

OUTPUT:
Integer. The number of players online on your game.

*/

function config_getGameStats_v1_onlinePlayers() {

	// Retrieve the number of online players
	$sql = "SELECT COUNT(*) AS OnlinePlayers FROM Accounts WHERE Online = 1";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	return $row['OnlinePlayers'];

} // config_getGameStats_v1_onlinePlayers

/*

DEFINE CONSTANTS: GETGAMESTATS_V1_CUSTOMSTAT#NAME

The following constants contain the name of any custom game-wide statistics you want displayed
on your PBBG Warp listing.

This sample code defines two custom game statistics: the number of battles fought today, and the
number quests completed.

All custom statistics are optional. You can set the name to null if you don't wish to
implement a particular custom statistic, as was done for statistics 3 to 5 in the code below.
Any custom statistics that you name here must have the corresponding functions completed
below so that the script can retrieve these statistics.

*/

define('GETGAMESTATS_V1_CUSTOMSTAT1NAME', 'Battles Today');
define('GETGAMESTATS_V1_CUSTOMSTAT2NAME', 'Quests Completed');
define('GETGAMESTATS_V1_CUSTOMSTAT3NAME', null);
define('GETGAMESTATS_V1_CUSTOMSTAT4NAME', null);
define('GETGAMESTATS_V1_CUSTOMSTAT5NAME', null);

/*

BUILD FUNCTION: config_getGameStats_v1_customStat1

If you are implementing this method remember to set constant IMPLEMENTED_GETGAMESTATS_V1 to true.

This function retrieves the current value of your custom statistic 1. It will only be called
if the constant GETGAMESTATS_V1_CUSTOMSTAT1NAME defined above is not null.

The sample code assumes that you have a table called BattlesToday, and it retrieves a count of
the number of rows in this table.

INPUT:
None.

OUTPUT:
The function should return the current value of your custom statistic 1. You can return a string,
integer, double, or boolean variable.

*/

function config_getGameStats_v1_customStat1() {

	// Retrieve the number of battles today
	$sql = "SELECT COUNT(*) AS NumBattles FROM BattlesToday";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	return $row['NumBattles'];

} // config_getGameStats_v1_customStat1

/*

BUILD FUNCTION: config_getGameStats_v1_customStat2

If you are implementing this method remember to set constant IMPLEMENTED_GETGAMESTATS_V1 to true.

This function retrieves the current value of your custom statistic 2. It will only be called
if the constant GETGAMESTATS_V1_CUSTOMSTAT2NAME defined above is not null.

The sample code assumes that you have a table called Quests with a column called Completed. The
function counts the number of quests that are completed, and returns the number.

INPUT:
None.

OUTPUT:
The function should return the current value of your custom statistic 2. You can return a string,
integer, double, or boolean variable.

*/

function config_getGameStats_v1_customStat2() {

	// Retrieve the number of quests completed
	$sql = "SELECT COUNT(*) AS NumQuestsCompleted FROM Quests WHERE Completed = 1";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	return $row['NumQuestsCompleted'];

} // config_getGameStats_v1_customStat2

/*

BUILD FUNCTION: config_getGameStats_v1_customStat{3,4,5}

If you are implementing this method remember to set constant IMPLEMENTED_GETGAMESTATS_V1 to true.

These functions allow you to retrieve custom game statistics 3 through 5.
Since these custom statistics were disabled when defining the statistic names above, they are
empty and will not be called under the current setup.

INPUT:
None.

OUTPUT:
The function should return the current value of your custom statistic (3|4|5). You can return a
string, integer, double, or boolean variable.

*/

function config_getGameStats_v1_customStat3() {

} // config_getGameStats_v1_customStat3

function config_getGameStats_v1_customStat4() {

} // config_getGameStats_v1_customStat4

function config_getGameStats_v1_customStat5() {

} // config_getGameStats_v1_customStat5

/****************************************
*
*   Your XML-RPC Server Method:
*   pbbgwarp.getPlayerStats_v1
*
****************************************/

/*

DEFINE CONSTANT: IMPLEMENTED_GETPLAYERSTATS_V1

The following constant allows you to enable and disable the pbbgwarp.getPlayerStats_v1 method on
your server. If you disable the method then you do not need to do any further configuration in
this section.

*** THE METHOD IS DISABLED BY DEFAULT ***

*/

define('IMPLEMENTED_GETPLAYERSTATS_V1', false);

/*

DEFINE CONSTANTS: GETPLAYERSTATS_V1_STAT#NAME, GETPLAYERSTATS_V1_STAT#SORT

The following constants describe the type of statistics you will return
for each player.

STAT#NAME is the name of the statistic.
	
STAT#SORT says whether a high or low value indicates a good performance.
	Must be 'high to low', 'low to high', or 'unsorted'.
	However, STAT1SORT cannot be 'unsorted'.
	
The second and third player statistics are optional, and can be disabled by setting
the corresponding constants to null, as was done for statistic 3 below.

*/

define('GETPLAYERSTATS_V1_STAT1NAME', 'Score');
define('GETPLAYERSTATS_V1_STAT1SORT', 'high to low'); // Cannot be 'unsorted'

define('GETPLAYERSTATS_V1_STAT2NAME', 'Location');
define('GETPLAYERSTATS_V1_STAT2SORT', 'unsorted');

define('GETPLAYERSTATS_V1_STAT3NAME', null);
define('GETPLAYERSTATS_V1_STAT3SORT', null);

/*

BUILD FUNCTION: config_getPlayerStats_v1

If you are implementing this method remember to set constant IMPLEMENTED_GETPLAYERSTATS_V1 to
true.

This function receives a screen name and retrieves the statistics for that player. If the screen
name requested no longer exists on your game then this function should return false. This
function will only be called for players who have verified their screen names (i.e. you must
implement the method pbbgwarp.isPlayerKeyValid_v1 below).

The sample code below assumes you have an Accounts table in your database with Username, Score,
and Location columns. A third player statistic is not returned in the sample code below since
its name and sort direction were set to null above.

INPUT:
$inScreenName	String. The screen name to retrieve statistics for.

OUTPUT:
Return an array with the following elements:
	stat1
	stat2 (only required if GETPLAYERSTATS_V1_STAT2NAME is set)
	stat3 (only required if GETPLAYERSTATS_V1_STAT3NAME is set)

stat1, stat2, and stat3 can return string, integer, double, or boolean data. However, each
statistic must have the same data type across all players (i.e. stat1 can't be 100 for John and
"Ten" for Bob).

*/

function config_getPlayerStats_v1($inScreenName) {

	// Load the score and location for $inScreenName
	$sql = "SELECT Score, Location FROM Accounts
			WHERE Username = '" . str_replace("'", "\'", $inScreenName) . "'";
	$query = mysql_query($sql);
	if (mysql_num_rows($query) == 0) {
		return false;
	} else {
		$row = mysql_fetch_assoc($query);
		$outArray = array ();
		$outArray['stat1'] = (int) $row['Score'];
		$outArray['stat2'] = (string) $row['Location'];
		return $outArray;
	}

} // config_getPlayerStats_v1

/****************************************
*
*   Your XML-RPC Server Method:
*   pbbgwarp.isPlayerKeyValid_v1
*
****************************************/

/*

DEFINE CONSTANT: IMPLEMENTED_ISPLAYERKEYVALID_V1

The following constant allows you to enable and disable the pbbgwarp.isPlayerKeyValid_v1 method
on your server. If you disable the method then you do not need to do any further configuration in
this section.

*** THE METHOD IS DISABLED BY DEFAULT ***

*/

define('IMPLEMENTED_ISPLAYERKEYVALID_V1', true);

/*

BUILD FUNCTION: config_isPlayerKeyValid_v1

If you are implementing this method remember to set constant IMPLEMENTED_GETGAMESTATS_V1 to true.

This function receives a screen name and a player key and checks your database to see if
the screen name exists and if the player key is valid.

The sample code below assumes you have an Accounts table in your database with Username and
PBBGWarpPlayerKey columns. PBBGWarpPlayerKey simply needs to hold a random string or number
for each of your players.

INPUT:
$inScreenName	String. The screen name to verify the player key against.
$inPlayerKey	String. The player key provided by the user on PBBG Warp.

OUTPUT:
Return boolean true if the screen name exists and the player key is valid.
Return boolean false if the screen name does not exist, or if the player key is invalid
*/

function config_isPlayerKeyValid_v1($inScreenName, $inPlayerKey) {
	global $dal;
	// Check if the screen name exists and the player key is valid
	$statement = $dal->prepare( 'SELECT count(*) ' .
			'FROM users ' .
			'WHERE username = :username AND pbbg_warp_random = :player_key' );
	$statement->bindParam( ':username', $inScreenName );
	$statement->bindParam( ':player_key', $inPlayerKey, PDO::PARAM_INT );

	if ( $dal->getValue( $statement ) == 1 ) {
		return true;
	}
	else {
		return false;
	}

} // config_isPlayerKeyValid_v1
// ALL DONE!
?>
